
package com.panfeng.xcloud.boss.provider.member.security.auth;

import com.panfeng.xcloud.common.security.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

/**
 *
 * springcloud oauth2 TokenStore具体实现配置类
 *
 * @author xiaobo
 * @version 1.0
 * @since 2018-12-28
 */
@Configuration
public class TokenStoreConfig {

	@Configuration
	@ConditionalOnProperty(prefix = "xdcloud.security.oauth2", name = "tokenStore", havingValue = "redis")
	public static class RedisConfig {

		@Autowired
		private RedisConnectionFactory redisConnectionFactory;

		@Bean
		public TokenStore redisTokenStore() {
			return new RedisTokenStore(redisConnectionFactory);
		}

	}

	@Configuration
	@ConditionalOnProperty(prefix = "xdcloud.security.oauth2", name = "tokenStore", havingValue = "jwt", matchIfMissing = true)
	public static class JwtConfig {

		@Autowired
		private SecurityProperties securityProperties;

		@Bean
		public TokenStore jwtTokenStore() {
			return new JwtTokenStore(jwtAccessTokenConverter());
		}

		/**
		 * @TODO:
		 * JwtAccessTokenConverter是用来生成token的转换器，
		 * 而token令牌默认是有签名的，且资源服务器需要验证这个签名。
		 * 此处的加密及验签包括两种方式：对称加密、非对称加密（公钥密钥）,
		 * 对称加密需要授权服务器和资源服务器存储同一key值
		 * @return
		 */
		@Bean
		public JwtAccessTokenConverter jwtAccessTokenConverter() {
			JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
			String jwtSigningKey = securityProperties.getOauth2().getJwtSigningKey();
			converter.setSigningKey(jwtSigningKey);
			return converter;
		}

		@Bean
		@ConditionalOnBean(TokenEnhancer.class)
		public TokenEnhancer jwtTokenEnhancer() {
			return new TokenJwtEnhancer();
		}

	}

}
